<?php

// $Id$

require_once(TANGRA_MAIN_DIR.'form/guardable_form.class.php');
require_once(TANGRA_MAIN_DIR.'web_site/web_page/just_headers_view.class.php');
require_once(TANGRA_MAIN_DIR.'form/form_ctrl.class.php');

require_once($WSC->get_site_inc_dir().'modules/admin_panel/site_admin_web_page_wed.class.php');


abstract class Site_Admin_Page_W_FCtrl extends Site_Admin_Web_Page_WED {
	protected $form_ctrl;
	private $redir_on_success;


	function __construct($page_name, $redir_on_success_target_page = '') {
		parent::__construct($page_name);

		$this->redir_on_success = $redir_on_success_target_page;
	}


	public function init() {
		parent::init();

		$v = $this->create_view();
		$this->add_view($v);

		$tvm = $this->get_tvm();

		$dbc = $this->get_dbc();

		$this->_create_form_ctrl();

		$event_submit = $this->form_ctrl->get_form_submit_event();
		$this->wed->add_wed_event_action_pair($event_submit, 'form_submit');

		$event_add_new = $this->form_ctrl->get_add_new_event();
		$this->wed->add_wed_event_action_pair($event_add_new, 'add_new_event');

		$event_object_id = $this->form_ctrl->get_object_id_event();
		$this->wed->add_wed_event_action_pair($event_object_id, 'receiving_object_id');

//printbr($event_object_id->get_capture());
	}


	protected function default_event() {
		$this->form_ctrl->prepare_for_show();
		$this->add_exports($this->form_ctrl->get_tple_exports());

		$view = $this->get_view('default');



		return $view;
	}


	protected function form_submit($params) {
		$context = $this->get__context();
		$rez = $this->form_ctrl->process_submit($context);

		if ($rez == Form_Ctrl::SUBMIT_RESULT_OK ) {
			if ($this->redir_on_success) {
				$redir = new Redirect_Composer_Local($this->get__context(), $this->redir_on_success);
				$view = new Just_Headers_View();
				$view->add_http_header($redir->get_location($this->get__context()));
			} else {
				$view = $this->form_submit_is_ok();
			}

			return $view;
		} else {
			return $this->default_event();
		}
	}


	protected function receiving_object_id($object_id) {
		tangra_if_not_int_throw_e($object_id);

		$this->form_ctrl->process_object_id($object_id);

		return $this->default_event();
	}


	protected function add_new_event() {
		return $this->default_event();
	}


	protected function _create_form_ctrl() {
		$form_ctrl = $this->create_form_ctrl();
		if ($form_ctrl instanceof Form_Ctrl ) {
			$this->form_ctrl = $form_ctrl;
		} else {
			throw new Tangra_User_Exception('Object returned by create_form_ctrl is not instance of Form_Ctrl.');
		}
	}


	protected function form_submit_is_ok() {
		return $this->default_event();
	}

	abstract protected function create_form_ctrl();
}